package com.sservice.web.controller.pc;

import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.sservice.base.SameUrlData;
import com.sservice.base.StringUtils;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.common.Code;
import com.sservice.commonBusiness.e.Category;
import com.sservice.commonBusiness.service.CategoryService;
import com.sservice.commonBusiness.type1.Category_TYPE;
import com.sservice.commonBusiness.vo.CategoryVo;
import com.sservice.model.dao.IOrderDao;
import com.sservice.model.dao.OfferVarsMapper;
import com.sservice.model.dao.OrderShopMapper;
import com.sservice.model.entity.*;
import com.sservice.model.vo.OfferVo;
import com.sservice.model.vo.OrderShopVo;
import com.sservice.model.vo.OrderVo;
import com.sservice.service.service.*;
import com.sservice.web.wechat.controller.WxPayController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Controller
@RequestMapping("/order")
public class OrderPcController {
    @Autowired
    OrderShopMapper orderShopMapper;
    @Autowired
    AddressService addressService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    IOfferService iOfferService;
    @Autowired
    OfferVarsMapper offerVarsMapper;
    @Autowired
    IOrderDao iOrderDao;
    @Autowired
    Redis redis;
    @Autowired
    WxPayController wxPayController;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private IOrderService depService;
    @Autowired
    private IUserWxService userWxService;

    @ResponseBody
    @RequestMapping(value = "/reUnifiedOrder", method = RequestMethod.GET)
    public BaseResult reUnifiedOrder(WxPayUnifiedOrderRequest orderRequest, HttpServletRequest request) throws WxPayException {
        String outTradeNo = orderRequest.getOutTradeNo();
        Order order = depService.selectOneByNo(outTradeNo);
        if (outTradeNo.length() == 19) {
            outTradeNo = outTradeNo + "0";
        } else {
            outTradeNo = outTradeNo.substring(0, 19) + (Integer.parseInt(outTradeNo.substring(19, 20)) + 1);
        }
        order.setNo(outTradeNo);
        depService.updateByPrimaryKeySelective(order);
        orderRequest.setOutTradeNo(outTradeNo);
        return wxPayController.unifiedOrder(orderRequest, request);
    }

    /***
     *  服务申请管理，分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryApply", method = RequestMethod.GET)
    public ListResult queryApply(OrderVo arg, String orderStatus, HttpSession session) {
        if (StringUtils.isBlank(arg.getSkey())) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(arg.getSkey());
        arg.setSaleId(salep.getId().toString());
        if ("0".equals(orderStatus)) { //全部商品
        } else if ("1".equals(orderStatus)) { //待支付
            arg.setPayStatus("0"); // 0未支付，1已支付
        } else if ("2".equals(orderStatus)) { //待收货
            arg.setPayStatus("1"); // 0 未收货，1待收货，2已收货
        } else if ("3".equals(orderStatus)) { //已完成
            arg.setPayStatus("-1");//
        }
        List<OrderVo> list_order = depService.queryPlainByPage(arg);
        int total = depService.countPlainByPage(arg);
        ListResult res = new ListResult(true, list_order);
        res.setPage(new Pagination(arg.getPage(), total, arg.getSize()));
        return res;
    }


    /**
     * 【多商品购买和发起拼团必须参数】区分多商品直接购买还是发起拼团。type值：
     * 1. 4 ：普通单商品直接购买
     * 2. 0 ：拼团单商品直接购买
     * 3. 1 ：多商品直接购买
     * 4. 2 ：发起拼团
     * 5. 3 ：加入拼团商品
     * <p>
     * 功能：
     * 1. 单商品直接购买:shopIds,sizes,numbers,skey,remark,deliverMethod,payTotal
     * 1.1. 非拼团单商品直接购买:shopIds,sizes,numbers,skey,remark,deliverMethod,payTotal
     * 2. 多商品直接购买: themeId ,type=1,skey,remark,deliverMethod,payTotal
     * 3. 发起拼团     : themeId,type=2,skey,remark,deliverMethod,payTotal
     * 4. 加入拼团     : id, type=3,themeId,skey,remark,deliverMethod,payTotal
     * 下单接口
     * <p>
     * 参数说明：
     * arg.gift         礼品卡号，参数传递时，表示使用礼品卡
     * arg.id          【加入拼团必穿】加入订单id
     * arg.type        【多商品购买和发起拼团必须参数】区分多商品直接购买还是发起拼团，1多商品购买，2发起拼团
     * arg.themeId     【多商品购买和发起拼团必须参数】主题ID，
     * arg.themeId     【多商品购买和发起拼团必须参数】主题ID，
     * arg.addressId   【必传】地址Id。必传
     * arg.skey        【必传】必传
     * arg.remark      【必传】备注说明
     * arg.deliverMethod【必传】配送方式
     * arg.payTotal    【必传】付款总金额
     * arg.numbers     【单商品必传】数量
     * arg.sizes       【【单商品必传】尺码
     * arg.shopIds     【单商品必传】商品ID
     *
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Object> create(OrderVo arg) {
        if (StringUtils.isBlank(arg.getSkey())) {
            return new BaseResult(false, "参数不合法，未携带skey参数", Code.NO_PERMISSION);
        }
        UserWx salep = userWxService.getLogined(arg.getSkey());
        if (salep == null) {
            return new BaseResult(false, "未登录 ", Code.NOT_LOGIN);
        }
        arg.setSaleId(String.valueOf(salep.getId()));
        arg.setSaleName(salep.getNickName());//
        Object str = depService.create(arg, salep);
        BaseResult res = null;//
        if (str instanceof String) {
            res = new BaseResult(false, str.toString(), Code.NO_PERMISSION);
        } else {
            res = new BaseResult(true, str);
        }
        return res;
    }

    /**
     * 微信支付异步通知接口
     *
     * @param arg
     * @return
     */
    @RequestMapping(value = "/wx-server-pay-notify", method = RequestMethod.GET)
    public BaseResult<Object> wxServerPayNotify(OrderVo arg) {

        return new BaseResult<>();
    }

    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/paySuccess/{no}/{transactionId}/{total}", method = RequestMethod.GET)
    public BaseResult<Object> paySuccess(OrderVo arg) {
        if (StringUtils.isBlank(arg.getSkey())) {
            return new BaseResult(false, "参数不合法，未携带skey参数", Code.NO_PERMISSION);
        }
        UserWx salep = userWxService.getLogined(arg.getSkey());
        if (salep == null) {
            return new BaseResult(false, "未登录 ", Code.NOT_LOGIN);
        }
        arg.setSaleId(String.valueOf(salep.getId()));
        return depService.paySuccess(arg);

    }

    /**
     * 申请服务
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/apply", method = RequestMethod.POST)
    public BaseResult<Object> apply(OrderVo arg) {
        if (StringUtils.isBlank(arg.getSkey())) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(arg.getSkey());
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        arg.setSaleId(String.valueOf(salep.getId()));
        arg.setSaleName(salep.getNickName());
        Object str = depService.apply(arg, salep);
        BaseResult res = null;//
        if (str instanceof String) {
            res = new BaseResult(false, str.toString(), 403);
        } else {
            res = new BaseResult(true, str);
        }
        return res;
    }


    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/exchange", method = RequestMethod.POST)
    public BaseResult<Object> exchange(OrderVo arg) {
        if (StringUtils.isBlank(arg.getSkey())) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(arg.getSkey());
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        arg.setSaleId(String.valueOf(salep.getId()));
        arg.setSaleName(salep.getNickName());
        arg.setType1("exchange");//兑换积分
        Offer offer = iOfferService.selectByPrimaryKey(arg.getId()); // 商品
        Address address = addressService.findById(Integer.valueOf(arg.getAddressId()));
        arg.setAddress(
                address.getProvince() + address.getCity() + address.getDetail() + "/" +
                        address.getPerson() + "/" +
                        address.getPhone()
        );
        arg.setOfferId(String.valueOf(arg.getId()));
        arg.setId(null);
        UserWx userWx = userWxService.selectByPrimaryKey(salep.getId());
        userWx.setPointsNow((userWx.getPointsNow().subtract(offer.getPrice())));
        userWxService.updateByPrimaryKeySelective(userWx);//合计内容

        Object str = depService.exchange(arg);
        BaseResult res = null;//
        redis.setObj(arg.getSkey(), userWx);
        if (str instanceof String) {
            res = new BaseResult(false, str.toString(), 403);
        } else {
            res = new BaseResult(true, str);
        }
        return res;

    }

    /**
     * 订单详情
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public BaseResult detail(OrderVo arg) {
        if (StringUtils.isBlank(arg.getSkey())) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(arg.getSkey());
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        return new BaseResult(true, depService.detail(arg.getId(), null));
    }

    @ResponseBody
    @RequestMapping(value = "/exchangeDetail", method = RequestMethod.GET)
    public BaseResult exchangeDetail(OrderVo arg) {
        if (StringUtils.isBlank(arg.getSkey())) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(arg.getSkey());
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        return new BaseResult(true, depService.exchangeDetail(arg.getId(), null));
    }


    /**
     * 我的订单
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryOrder", method = RequestMethod.GET)
    public ListResult<Object> queryOrder(OrderVo arg, String orderStatus) {
        if (StringUtils.isBlank(arg.getSkey())) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(arg.getSkey());
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        // 订单状态：0全部订单，1待支付，2待收货，3已完成
        if ("0".equals(orderStatus)) { //全部商品
        } else if ("1".equals(orderStatus)) { //待支付
            arg.setPayStatus("0"); // 0未支付，1已支付
        } else if ("2".equals(orderStatus)) { //待收货
            arg.setPayStatus("1"); // 0 未收货，1待收货，2已收货
        } else if ("3".equals(orderStatus)) { //已完成
            arg.setPayStatus("-1");//
        }
        ListResult<Object> res;
        arg.setSaleId(String.valueOf(salep.getId()));
        List<OrderVo> list = depService.queryMyOrdersByPage(arg);
//        list = list.stream().map(item -> {
//            if ("0".equals(item.getPayStatus())) {
//                if ("-1".equals(item.getStatus())) {
//                    item.setStatus("已取消");
//                } else {
//                    item.setStatus("待支付");
//                }
//            } else if ("1".equals(item.getPayStatus())) {
//                if ("1".equals(item.getStatus()) || "1".equals(item.getDeliverStatus())) {
//                    item.setStatus("已完成");
//                } else if ("0".equals(item.getDeliverStatus())) {
//                    item.setStatus("待收货");
//                }
//            }
//            return item;
//        }).collect(Collectors.toList());
        int total = depService.queryMyOrderCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }


    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/add-address", method = RequestMethod.POST)
    public BaseResult<Object> addAddress(Address arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        arg.setOwnerid(salep.getId().toString()); //
        return new BaseResult(true, addressService.insert(arg));
    }

    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/detail-address", method = RequestMethod.GET)
    public BaseResult<Object> detailAddress(Address arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        arg.setOwnerid(salep.getId().toString()); //
        return new BaseResult(true, addressService.findById(arg.getId()));
    }

    /**
     * 修改地址
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/update-address", method = RequestMethod.POST)
    public BaseResult<Object> updateAddress(Address arg, String skey) {
//        SalePerson salep = (SalePerson) session.getAttribute(Constants.CURRENT_SP);
        if (StringUtils.isBlank(skey)) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        arg.setOwnerid(salep.getId().toString());//
        return new BaseResult(true, addressService.update(arg));
    }

    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/remove-address", method = RequestMethod.POST)
    public BaseResult<Object> removeAddress(Address arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        arg.setOwnerid(salep.getId().toString());//
        return new BaseResult(true, addressService.remove(arg.getId()));
    }

    /**
     * 地址列表
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/list-address", method = RequestMethod.GET)
    public BaseResult<Object> listAddress(Address arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        arg.setOwnerid(salep.getId().toString());//
        return new BaseResult(true, addressService.list(arg));
    }


    /**
     * 激活礼品卡
     *
     * @param no
     * @param skey
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/activateGift", method = RequestMethod.POST)
    public BaseResult<Object> activateGift(String no, String skey, Integer type1) {
        if (StringUtils.isBlank(skey)) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        Category category = new Category();
        category.setEn(no);
        category.setSysId(salep.getId());
        category.setType1(type1);

        try {
            Object res = depService.queryGift(category);
            if (res instanceof String) {
                return new BaseResult(false, res.toString(), 403);
            }
            return new BaseResult(true, 1 + "", 200);

        } catch (Exception e) {
            return new BaseResult(false, e.getMessage() != null ? e.getMessage() : "兑换失败", 403);
        }

    }

    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/queryGift", method = RequestMethod.GET)
    public ListResult queryGift(CategoryVo arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new ListResult(false, "未登录 ", 401);
        }
        if ("coupon".equals(arg.getType1()) || "gift".equals(arg.getType1())) {
            arg.setType1("gift".equals(arg.getType1()) ? Category_TYPE.TYPE_GIFT.getValue() : Category_TYPE.TYPE_COUPON.getValue());
            arg.setSourceId(salep.getId().toString());
            arg.setDataRtype1("gift".equals(arg.getType1()) ? "d_r_gift" : "dr_coupon");
        }
        List res = depService.queryCategory(arg);
        return new ListResult(true, res);
    }

    /**
     * 微信支付
     *
     * @param arg
     * @param skey
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/weChatAppletPay", method = RequestMethod.GET)
    public ListResult weChatAppletPay(CategoryVo arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new ListResult(false, "未登录 ", 401);
        }
        if ("coupon".equals(arg.getType1()) || "gift".equals(arg.getType1())) {
            arg.setType1("gift".equals(arg.getType1()) ? Category_TYPE.TYPE_GIFT.getValue() : Category_TYPE.TYPE_COUPON.getValue());
            arg.setSourceId(salep.getId().toString());
            arg.setDataRtype1("gift".equals(arg.getType1()) ? "d_r_gift" : "dr_coupon");
        }
        List res = depService.queryCategory(arg);
        return new ListResult(true, res);
    }

    /**
     * 加入购物车
     * 1. 拼团商品加入购物车
     * 2. 普通商品加入购物车
     *
     * @param arg
     * @param skey
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/addShoppingcart", method = RequestMethod.POST)
    public BaseResult<Object> addShoppingcart(OrderShop arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        arg.setSpId(salep.getId().toString());
        arg.setType1("cart");// 加入购物车数据
        Object obj = depService.addShopCart(arg);
        if (obj instanceof String) {
            return new BaseResult(false, obj.toString(), 403);

        } else {
            return new BaseResult(true, obj);

        }
    }

    /**
     * 购物车中商品
     * <p>
     * 1.拼团商品的
     *
     * @param arg
     * @return
     */
    @ResponseBody
//    @SameUrlData
    @RequestMapping(value = "/shoppingcartItems", method = RequestMethod.GET)
    public Map shoppingcartItems(OrderShop arg, String skey, String deliverPlace) {
        Map map = new HashMap();
        if (StringUtils.isBlank(skey)) {
            map.put("code", 403);
            map.put("error", "参数不合法，未携带skey参数");
            return map;
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            map.put("code", 403);
            map.put("error", "未登录");
            return map;
        }
        arg.setSpId(salep.getId().toString());
        arg.setType1("cart");// 购物车
        List<OfferVo> list = depService.getShopCarts(arg);
        map.put("code", "200");
        map.put("list", list);
        map.put("outCome", false);// 拼团价
        BigDecimal totalPrice = BigDecimal.ZERO;
//        BigDecimal totalActualPrice = BigDecimal.ZERO;
//        BigDecimal totalPtPrice = BigDecimal.ZERO;//
        for (OfferVo of : list) { //  合计价格
            totalPrice = totalPrice.add(BigDecimal.valueOf(Double.valueOf(of.getNumberSelected())).multiply((of.getPrice())));
        }
        map.put("totalPrice", totalPrice);// 总原价
        return map;
    }

    /**
     * 从购物车中移除
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/removeShoppingcart", method = RequestMethod.POST)
    public BaseResult<Object> removeShoppingcart(OrderShop arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        return new BaseResult(true, depService.removeShopCart(arg));
    }


    /**
     * 某一个主题下正在进行的拼团
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/ongoGroupshopping", method = RequestMethod.GET)
    public BaseResult<Object> ongoGroupshopping(OrderVo arg) {
        if (StringUtils.isBlank(arg.getSkey())) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(arg.getSkey());
        if (salep == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        if (StringUtils.isBlank(arg.getThemeId())) {
            return new BaseResult(false, "请传递themeId ", 403);
        }

        List<OrderVo> list = depService.selectOngoingPcByThemeId(arg.getThemeId(), salep.getId().toString());
        for (OrderVo orderVo : list) {
            orderVo.setEndDate((orderVo.getEndTime().getTime() - System.currentTimeMillis()) + "");
        }
        return new BaseResult(true, list);
    }


    /**
     * 某个主题拼团中的订单
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/onGoging", method = RequestMethod.GET)
    public ListResult themeGrouping(OrderShop arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录", 401);
        }
        arg.setSizeId(salep.getId().toString());// 排除当前登录用户发起的拼团
        List<OrderVo> list = depService.selectOngoingPcByThemeId(arg.getThemeId(), salep.getId().toString());
        for (OrderVo orderVo : list) {
            orderVo.setEndDate((orderVo.getEndTime().getTime() - System.currentTimeMillis()) + "");
        }
        return new ListResult(true, list);
    }

    /**
     * @param arg
     * @param skey
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/group", method = RequestMethod.GET)
    public ListResult group(OrderVo arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录", 401);
        }
        arg.setSaleId(salep.getId().toString());
        //arg.setStatus("0");
        List<OrderVo> list = depService.selectGroupOrder(arg);
        long now = System.currentTimeMillis();
        list = list.stream().map(ele -> {
            ele.setOverPlusTime(now - ele.getEndTime().getTime());// 剩余时间
            return ele;
        }).collect(Collectors.toList());
        ListResult listResult = new ListResult(true, list);
        listResult.setPage(new Pagination(arg.getPage(), arg.getSize(), arg.getSize()));
        return listResult;
    }

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/detailByNo", method = RequestMethod.GET)
    public BaseResult detailByNo(OrderVo arg) {
        if (StringUtils.isBlank(arg.getSkey())) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(arg.getSkey());
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        return new BaseResult(true, depService.detail(0, arg.getNo()));
    }

    /**
     * 同步时钟
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/SynTime", method = RequestMethod.GET)
    public BaseResult SynTime() {
        return new BaseResult(true, System.currentTimeMillis());
    }

    /**
     * 修改购物车中商品数量
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/updateCartShopNum", method = RequestMethod.POST)
    public ListResult updateCartShopNum(OrderShop arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        return new ListResult(true, depService.updateCartShopNum(arg));
    }


    /**
     * 购物中商品选中与否
     * arg.status 1 选中，0 未选中
     *
     * @param arg  id 购物车中物品id
     * @param skey
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/shop-item-check", method = RequestMethod.POST)
    public BaseResult shopItemCheck(OrderShop arg, String skey, String ids) {
        if (StringUtils.isBlank(skey)) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new BaseResult(false, "未登录 ", 401);
        }
        arg.setSpId(salep.getId().toString());
        Object o = depService.shopItemCheck(arg, ids);
        if (o instanceof String) {
            return new BaseResult(false, o.toString(), 403);
        } else {
            return new BaseResult(true, o);
        }
    }


    /**
     * 购物车中已选中商品的供货地集合
     *
     * @param checked
     * @param skey
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/getDeliverPlaceCheckedInCart", method = RequestMethod.GET)
    public ListResult getDeliverPlaceCheckedInCart(String checked, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        OrderShop orderShop = new OrderShop();
        orderShop.setSpId(salep.getId().toString());
        List<Category> o = orderShopMapper.getDeliverPlaceCheckedInCart(orderShop);
        return new ListResult(true, o);
    }


    /**
     * 选取某一个购货地选中状态的的订单
     *
     * @param delverPlace
     * @param skey
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/dealItemsDeliverPlaceCheckedInCart", method = RequestMethod.GET)
    public ListResult dealItemsDeliverPlaceCheckedInCart(String delverPlace, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        OrderShopVo orderShop = new OrderShopVo();
        orderShop.setSpId(salep.getId().toString());
        orderShop.setDeliverPlace(delverPlace);
        List<OrderShopVo> o = orderShopMapper.dealItemsDeliverPlaceCheckedInCart(orderShop);
        return new ListResult(true, o);
    }


    /**
     * 直接购买商品数据
     *
     * @param skey
     * @param id
     * @param sizeId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/direct-buy-offer-data", method = RequestMethod.POST)
    public BaseResult directBuyOfferData(String skey, Integer id, String sizeId) {

        OfferVo offerVo = iOfferService.selectByPrimaryKey(id);
        offerVo.setSizeId(sizeId);
        OfferVars offerVars = new OfferVars();
        String ids = Stream.of(sizeId.split(",")).sorted(Comparator.comparing(item -> Integer.valueOf(item))).collect(Collectors.joining(","));

        offerVars.setVars(ids);
        offerVars.setOfferId(offerVo.getId().toString());
        offerVars = offerVarsMapper.selectOneBy(offerVars);
        offerVo.setSizeIdName(offerVars.getName());//
        offerVo.setPrice(offerVars.getPrice());
        offerVo.setActualPrice(offerVars.getActualPrice());
        offerVo.setPtPrice(offerVars.getPtPrice());
        offerVo.setDeliverName(categoryService.selectByPrimaryKey(Integer.valueOf(offerVo.getDeliverPlace())).getName());
        Map map = new HashMap();
        offerVo.setBrandName(categoryService.selectByPrimaryKey(Integer.valueOf(offerVo.getBrand())).getName());// 品牌
        map.put("offer", offerVo);
        map.put("deliverMethod", this.deliverPlace(offerVo.getDeliverPlace()).getList());
        return new BaseResult(true, map);
    }


    /**
     * 根据供货地获取配送方式
     *
     * @param delverPlace
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/deliverPlace", method = RequestMethod.GET)
    public ListResult deliverPlace(String delverPlace) {

        try {
            Category category = new Category();
            category.setId(Integer.valueOf(delverPlace));
            category.setType1(Category_TYPE.TYPE_COUNTRY.getValue());

            Category o = categoryService.selectBy(category);
            if (o != null) {
                if ("5".equals(o.getLevel())) { //国内城市
                    List list = new ArrayList();
                    Map map = new HashMap();
                    map.put("name", "顺丰包邮");
                    map.put("cost", "0");
                    list.add(map);
                    return new ListResult(true, list);
                } else { //国外
                    List list = new ArrayList();
                    Map map = new HashMap();
                    map.put("name", "国际标准");
                    map.put("cost", "0");
                    list.add(map);
                    Map map2 = new HashMap();
                    map2.put("name", "国际快捷（¥169）");
                    map2.put("cost", "169");
                    list.add(map2);
                    return new ListResult(true, list);
                }
            } else {
                return new ListResult(true, new ArrayList());
            }

        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            return new ListResult(false, "服务端错误!", 500);
        }
    }


    /**
     * 某个用户，某个主题喜爱
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/shopInCart", method = RequestMethod.GET)
    public ListResult shopInCart(OrderShop arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        try {
            return new ListResult(true, depService.ongoGroupshoping(arg));
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            return new ListResult(false, "服务端错误!", 500);
        }
    }

    /**
     * 申请退款
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/applyBack/{id}", method = RequestMethod.POST)
    public BaseResult<Object> applyBack(Order arg) {
        //SalePerson salep = (SalePerson) session.getAttribute(Constants.CURRENT_SP);
        return new BaseResult(false, "此功能已关闭，请联系管理员", 403);
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult<Order> query(OrderVo arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        List<OrderVo> list = depService.queryByPage(arg);
        int total = depService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<Order> res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryWithOffer", method = RequestMethod.GET)
    public ListResult<Order> queryWithOffer(OrderVo arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        arg.setSaleId(salep.getSaleId());
        List<OrderVo> list = depService.queryWithOfferByPage(arg);
        int total = depService.countWithOfferByPage(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<Order> res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }


}
